import * as echarts from 'echarts/lib/echarts';
export const merge = (arr, property = 'dataType') => {
  let keys = Array.from(new Set(arr.map((item) => item.key)));
  let names = Array.from(new Set(arr.map((item) => item.name)));
  let ObjKeyNames = {};
  arr.map((item) => {
    ObjKeyNames[item.name] = { ...item };
  });
  let keyNames = [];
  keys.map((key) => {
    let map = {};
    names.map((name) => {
      map = { ...map, [`${key}${name}`]: `${key}/${name}` };
    });
    keyNames.push(Object.values(map));
  });

  let data = arr.map((item) => ({ ...item, keyName: `${item.key}/${item.name}` }));

  let mapResultData = keyNames.flat().map((item) => {
    let findItem = data.filter((record) => record.keyName === item);
    let flag = findItem.length > 0 ? findItem[0] : false;
    if (!flag) {
      let [key, name] = item.split('/');
      return {
        ...ObjKeyNames[name],
        key,
        name,
        keyName: item,
        list: initDataList(arr[0].list, key, true),
      };
    }
    return findItem[0];
  });
  let result = mapResultData.reduce((res, item) => {
    let hasValue = res.findIndex((current) => {
      return current[property] === item[property];
    });
    hasValue !== -1
      ? (res[hasValue] = {
          ...res[hasValue],
          color: item.color,
          list: [...res[hasValue].list, ...initDataList(item.list, item.key)],
          key: `${res[hasValue].key}/${item.key}`,
        })
      : res.push({
          ...item,
          list: initDataList(item.list, item.key),
        });
    return res;
  }, []);
  return result;
};

const initDataList = (data = [], key, flag = false) => {
  let emptyInitDataList = flag
    ? { value: null, valueColor: null, valueIndex: null, valueNo: null }
    : {};
  let list = data.map((item) => ({
    ...item,
    _xAxis: `${key} ${item.xAxis}`,
    ...emptyInitDataList,
  }));
  return list;
};

export const stackMerge = (list) => {
  let data = list.map((item) => {
    return { ...item, stack: item.name.split('-')[0] };
  });
  return data;
};

export const mergeProperty = (data, property) => {
  let result = data.reduce((res, item) => {
    let hasValue = res.findIndex((current) => {
      return current[property] === item[property];
    });
    hasValue !== -1
      ? (res[hasValue] = {
          ...res[hasValue],
          fu: item.value,
          fuIndex: item.data.index,
          fuColorRich: item.data.colorRich,
        })
      : res.push(item);
    return res;
  }, []);
  return result;
};

//正负偏差转为二维数组
const doubleArray = (data, property) => {
  let result = Object.values(
    data.reduce((res, item) => {
      res[item[property]] ? res[item[property]].push(item) : (res[item[property]] = [item]);
      return res;
    }, {}),
  );
  return result;
};

const mergexAxisPointProperty = (arr, property) => {
  let _valueKey = property === '_xAxis' ? 'valueIndex' : 'evaluationIndex';
  let resultData = doubleArray(arr, 'dataType');
  let mapResultData = resultData.map((data) => {
    let result = data.reduce((res, item) => {
      let value = item[_valueKey];
      let dataSourceId = item.dataSourceId || 'dataSourceId';
      if (value === null) value = 9999999;
      let hasValue = res.findIndex((current) => {
        return current[property] === item[property];
      });
      hasValue !== -1
        ? res[hasValue].data.push({ key: dataSourceId, value })
        : res.push({
            [property]: item[property],
            data: [{ key: dataSourceId, value }],
          });
      return res;
    }, []);
    return result;
  });

  return mapResultData;
};

export const mergexAxisPoint = (mapData, type = 'list') => {
  if (mapData.length > 0) {
    let dataResult = [];
    mapData.map((record) =>
      record[type].map((item) => {
        dataResult.push({ ...item, dataType: record.dataType, dataSourceId: record.dataSourceId });
      }),
    );
    let data = dataResult;
    let property = type == 'list' ? '_xAxis' : 'stationId';
    let pointDataArr = mergexAxisPointProperty(data, property);
    let sortArr = [];
    pointDataArr.map((data) => {
      let resultArr = [];
      data.map((item) => {
        let result = {};
        let prescore = -1; //预定义值
        let ranking = 0; //排名
        let _data = item.data.sort((a, b) => {
          return a.value - b.value;
        });
        _data.map((record) => {
          let value = '';
          let _item = record.value === 9999999 ? '' : record.value;
          if (String(_item).length) {
            if (_item == prescore) {
              value = ranking;
            } else {
              ranking++;
              prescore = _item;
              value = ranking;
            }
          }
          result = { ...result, [property]: item[property], [record.key]: value };
        });
        resultArr.push(result);
      });
      sortArr = [...sortArr, resultArr];
    });
    return sortArr;
  }
};

export const ToFixed = (data, persion = 3) => {
  if (!data) return '-';
  return Number(data).toFixed(persion);
};

export const DragLine = (
  myChart,
  id,
  yAxisData,
  updatePosition,
  renovate,
  dragChangeList,
  maxCapacity,
) => {
  // 拖拽

  setTimeout(function () {
    myChart.setOption({
      graphic: echarts.util.map(yAxisData, function (item, dataIndex) {
        let position = myChart.convertToPixel({ seriesIndex: 0 }, [dataIndex, item]);
        return {
          id: dataIndex,
          type: 'circle',
          position: position,
          shape: {
            r: 5,
          },
          invisible: true,
          draggable: true,
          ondrag: echarts.util.curry(onPointDragging, dataIndex),
          onmousemove: echarts.util.curry(showTooltip, dataIndex),
          onmouseout: echarts.util.curry(hideTooltip, dataIndex),
          ondragend: echarts.util.curry(onPointDragEnd, dataIndex),
          z: 100,
        };
      }),
    });
  }, 0);

  myChart.on('dataZoom', updatePosition);
  // window.addEventListener('resize', updatePosition);

  // function updatePosition() {
  //     myChart.setOption({
  //         graphic: echarts.util.map(yAxisData, function (item, dataIndex) {
  //             return {
  //                 position:myChart.convertToPixel({ seriesIndex: 0 }, [dataIndex, item])
  //             };
  //         })
  //     })
  // }

  function showTooltip(dataIndex) {
    myChart.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: dataIndex,
    });
  }

  function hideTooltip() {
    myChart.dispatchAction({
      type: 'hideTip',
    });
  }

  function onPointDragging(dataIndex) {
    let nextNumber = Math.max(
      -999999999,
      myChart.convertFromPixel({ seriesIndex: 0 }, this.position)[1],
    );
    if (maxCapacity) {
      nextNumber = Math.min(maxCapacity, nextNumber);
    }
    yAxisData[dataIndex] = nextNumber;
    myChart.setOption({
      series: [
        {
          id: id,
          data: yAxisData,
        },
      ],
    });
  }
  function onPointDragEnd() {
    if (dragChangeList) {
      dragChangeList();
    }
    renovate.isRenovate = true;
    myChart.setOption({
      graphic: echarts.util.map(yAxisData, function (item, dataIndex) {
        return {
          id: dataIndex,
          position: myChart.convertToPixel({ seriesIndex: 0 }, [dataIndex, item]),
        };
      }),
    });
  }
};
